package com.framerock.db;

import com.framerock.baselib.Config;
import com.framerock.baselib.Rock;

public class DB {
    public static String DBBASE  = "";          //当前数据库
    public static String PERFIX  = "";          //数据库表名前缀
    public static String NOWSQL  = "";          //当前sql
    public static String TYPE     = "";          //数据库类型，默认mysql
    public static String CHARSET = "utf8mb4";      //字符集

    public static void initConf()
    {
        DB.DBBASE   = Config.getConfig("db.base");
        DB.PERFIX   = Config.getConfig("db.perfix");
        DB.TYPE     = Config.getConfig("db.type");
        DB.CHARSET  = Config.getConfig("db.charset", DB.CHARSET);
    }

    /**
     * 获取数据库连接对象
     * */
    public static DBConn getDbobj(String drive)
    {
        DBConn db;
        if(drive.equals("sqlite")) {
            db = new DBConnSqlite();
        }else if(drive.equals("mssql")){
            db = new DBConnMssql();
        }else{
            db = new DBConnMySql();
        }
        return db;
    }
    public static DBConn getDbobj()
    {
        return getDbobj(DB.TYPE);
    }

    /**
     * 加前缀
     * */
    public static String chuliPerfix(String table)
    {
        table = DB.PERFIX + table;
        return table;
    }

    /**
     * 表名加``
     * */
    public static String chuliTable(String table)
    {
        if(!Rock.contain(table, "`"))table = "`"+table+"`";
        return table;
    }

    /**
     * 条件处理
     * */
    public static String chuliWhere(String where)
    {
        if(!Rock.contain(where, "="))where = "`id`="+where+"";
        return where;
    }

    /**
     * 处理字段
     * */
    public static String chuliFields(String fields)
    {
        if(Rock.isEmpt(fields))fields = "*";
        if(Rock.contain(fields, ",") && fields.indexOf("`")==-1){
            String arr[] = fields.split(","),nstr = "",str;
            for(int i=0; i<arr.length; i++){
                str = arr[i];
                if(str.indexOf("`")==-1 && str.indexOf(" ")==-1 && str.indexOf("as")==-1){
                    nstr+=",`"+str+"`";
                }else{
                    nstr+=","+str+"";
                }
            }
            if(nstr.length()>0)fields = nstr.substring(1);
        }
        return fields;
    }

    /**
     * 字符串包含
     * */
    public static String dbInstr(String fields,  String val)
    {
        return "INSTR(CONCAT(',', "+fields+", ','), ',"+val+",')>0";
    }

    /**
     * 定义一个sql
     * */
    public static String dbSql(String table, String fields, String where)
    {
        String str = "SELECT "+chuliFields(fields)+" FROM "+chuliTable(table)+" WHERE "+where+"";
        return str;
    }
}
